package srv

import (
	"arc_srv4/common"
	"arc_srv4/logutils"
	"fmt"
	uuid "github.com/iris-contrib/go.uuid"
	"github.com/kataras/iris/v12"
	"go.uber.org/zap"
	"mime/multipart"
	"os"
	"strings"
)

var filePath = ""

// 判断文件夹是否存在
func pathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// 判断并创建文件夹
func makeDir(path string) bool {
	ib, err := pathExists(path)
	if err != nil {
		logutils.Logger.Error("check path exists error", zap.String("error", err.Error()))
		return false
	}
	if !ib {
		err := os.MkdirAll(path, os.ModePerm)
		if err != nil {
			logutils.Logger.Error("make dir path error", zap.String("path", path), zap.String("error", err.Error()))
			return false
		} else {
			logutils.Logger.Info("make dir path success", zap.String("path", path))
			return true
		}
	}
	return true
}

func UploadAttachment(ctx iris.Context) {
	filePath = common.AppConCfg.Attachment + common.ATTACH_PICS + "/"
	if !makeDir(filePath) {
		logutils.Logger.Error("upload error.make dir check failed")
		_, _ = ctx.JSON(common.ApiRspOnly{Code: 500, Message: "上传失败"})
		return
	}
	// 判断参数 上传文件时，数据在form-data中，数据类型 map[string][]string
	maps := ctx.Request().Form["code"]
	if len(maps) == 0 {
		_, _ = ctx.JSON(common.ApiRspOnly{Code: 500, Message: "缺少code参数，请检查"})
		return
	}
	code := maps[0]
	if code == "" {
		_, _ = ctx.JSON(common.ApiRspOnly{Code: 500, Message: "缺少code参数，请检查"})
		return
	}
	num, err := ctx.UploadFormFiles(filePath, beforeSave)
	if err != nil {
		logutils.Logger.Error("upload error", zap.Int64("size", num), zap.String("error", err.Error()))
		_, _ = ctx.JSON(common.ApiRspOnly{Code: 500, Message: "上传失败"})
		return
	}
	logutils.Logger.Info("upload success", zap.Int64("size", num))
	_, _ = ctx.JSON(common.ApiRspOnly{Code: 200, Message: "上传成功"})
}

func beforeSave(ctx iris.Context, file *multipart.FileHeader) {
	ip := ctx.RemoteAddr()
	ip = strings.Replace(ip, ".", "_", -1)
	ip = strings.Replace(ip, ":", "_", -1)

	ul, _ := uuid.NewV4()
	u2 := strings.ReplaceAll(fmt.Sprintf("%s", ul), "-", "")

	name := ip + "_" + u2 + "_" + file.Filename
	file.Filename = name
	logutils.Logger.Info("正在上传", zap.String("name", name))
	_, _ = ctx.Writef("|%s", filePath+file.Filename)
}
